package com.spzx.channel.service.impl;

import com.alibaba.fastjson2.JSON;
import com.spzx.channel.configure.ThreadPoolConfig;
import com.spzx.channel.domain.ItemVo;
import com.spzx.channel.service.IItemService;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.product.api.RemoteProductService;
import com.spzx.product.api.domain.Product;
import com.spzx.product.api.domain.ProductDetails;
import com.spzx.product.api.domain.ProductSku;
import com.spzx.product.api.domain.vo.SkuPrice;
import com.spzx.product.api.domain.vo.SkuStockVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

@Service
@Slf4j
public class ItemServiceImpl implements IItemService {

    @Autowired
    private RemoteProductService remoteProductService;
    @Autowired
    ThreadPoolExecutor threadPoolExecutor;
    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public ItemVo item(Long skuId) throws Exception {

        String key = "sku:product:data";
        //远程调用商品微服务接口之前 提前知道用户访问商品SKUID是否存在
        Boolean bit = redisTemplate.opsForValue().getBit(key, skuId);
        if (!bit) {
            //查询数据不存在直接返回空对象
            throw new ServiceException("查询的数据不存在！");
        }

        ItemVo itemVo = new ItemVo();

        CompletableFuture<ProductSku> productSkuCompletableFuture = CompletableFuture.supplyAsync(() -> { //没有参数，有返回结果
            //任务1.获取sku信息
            R<ProductSku> productSkuResult = remoteProductService.getProductSku(skuId, SecurityConstants.INNER);
            if (R.FAIL == productSkuResult.getCode()) {  //远程返回结果状态码是500，那么表示降级处理了
                throw new ServiceException(productSkuResult.getMsg()); //抛异常给controller，继续抛给统一异常处理类。
            }
            ProductSku productSku = productSkuResult.getData();
            itemVo.setProductSku(productSku);
            return productSku;
        }, threadPoolExecutor);

        CompletableFuture<Void> productResultCompletableFuture = productSkuCompletableFuture.thenAcceptAsync((productSku) -> { //有输入参数，不需要返回结果
            //任务2.获取商品信息
            R<Product> productResult = remoteProductService.getProduct(productSku.getProductId(), SecurityConstants.INNER);
            if (R.FAIL == productResult.getCode()) {
                throw new ServiceException(productResult.getMsg());
            }
            Product product = productResult.getData();
            itemVo.setProduct(product);
            itemVo.setSliderUrlList(Arrays.asList(product.getSliderUrls().split(",")));
            itemVo.setSpecValueList(JSON.parseArray(product.getSpecValue()));
        }, threadPoolExecutor);


        CompletableFuture<Void> skuPriceResultCompletableFuture = CompletableFuture.runAsync(() -> {  //不需要参数，没有返回结果
            //任务3.获取商品最新价格
            R<SkuPrice> skuPriceResult = remoteProductService.getSkuPrice(skuId, SecurityConstants.INNER);
            if (R.FAIL == skuPriceResult.getCode()) {
                throw new ServiceException(skuPriceResult.getMsg());
            }
            SkuPrice skuPrice = skuPriceResult.getData();
            itemVo.setSkuPrice(skuPrice);
        }, threadPoolExecutor);

        CompletableFuture<Void> productDetailsResultCompletableFuture = productSkuCompletableFuture.thenAcceptAsync((productSku) -> {
            //任务4.获取商品详情
            R<ProductDetails> productDetailsResult = remoteProductService.getProductDetails(productSku.getProductId(), SecurityConstants.INNER);
            if (R.FAIL == productDetailsResult.getCode()) {
                throw new ServiceException(productDetailsResult.getMsg());
            }
            ProductDetails productDetails = productDetailsResult.getData();
            itemVo.setDetailsImageUrlList(Arrays.asList(productDetails.getImageUrls().split(",")));
        }, threadPoolExecutor);

        CompletableFuture<Void> skuSpecValueResultCompletableFuture = productSkuCompletableFuture.thenAcceptAsync((productSku) -> {
            //任务5.获取商品规格对应商品skuId信息
            R<Map<String, Long>> skuSpecValueResult = remoteProductService.getSkuSpecValue(productSku.getProductId(), SecurityConstants.INNER);
            if (R.FAIL == skuSpecValueResult.getCode()) {
                throw new ServiceException(skuSpecValueResult.getMsg());
            }
            Map<String, Long> skuSpecValueMap = skuSpecValueResult.getData();
            itemVo.setSkuSpecValueMap(skuSpecValueMap);
        }, threadPoolExecutor);

        CompletableFuture<Void> skuStockResultCompletableFuture = productSkuCompletableFuture.thenAcceptAsync((productSku) -> {
            //任务6.获取商品库存信息
            R<SkuStockVo> skuStockResult = remoteProductService.getSkuStock(skuId, SecurityConstants.INNER);
            if (R.FAIL == skuStockResult.getCode()) {
                throw new ServiceException(skuStockResult.getMsg());
            }
            SkuStockVo skuStockVo = skuStockResult.getData();
            itemVo.setSkuStockVo(skuStockVo);
            productSku.setStockNum(skuStockVo.getAvailableNum());
        }, threadPoolExecutor);

        //阻塞主线程，6个异步全部完成，继续执行主线程任务。
        CompletableFuture.allOf(
                productSkuCompletableFuture,
                productResultCompletableFuture,
                skuPriceResultCompletableFuture,
                productDetailsResultCompletableFuture,
                skuSpecValueResultCompletableFuture,
                skuStockResultCompletableFuture
        ).join();
        return itemVo;
    }
}